package server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

	private ServerSocket server;
	
	public Server() {
		try {
			this.server = new ServerSocket(8199);
			
			int i = 1;
			while (true) {
				Socket incoming = server.accept();
				
				System.out.println("Spawning " + i);
				
				Runnable r = new ThreadEchoHandler(incoming, i);
				(new Thread(r)).start();
				
				i++;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	class ThreadEchoHandler implements Runnable {
		private Socket s;
		private int order;
		
		public ThreadEchoHandler(Socket s, int order) {
			this.s = s;
			this.order = order;
		}
		
		public void run() {
			try {
				try {
					Scanner in = new Scanner(s.getInputStream());
					PrintWriter out = new PrintWriter(s.getOutputStream());
					
					boolean done = false;
					while (!done && in.hasNextLine()) {
						String line = in.nextLine();
						System.out.println(order + " said: " + line);
						
						if (line.trim().equalsIgnoreCase("BYE")) {
							done = true;
						}
					}
				} finally {
					s.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		Server server = new Server();
	}
}
